package colaborativo.ondefica;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;

import android.util.Log;

public class JSONfunctions{		
	
	public static JSONArray getJSONfromURL(String url, String sql) {
	    InputStream is = null;
	    String result = "";
	    JSONArray jArray = null;

		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(url);
		 
		try {
			// Add your data
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("query", sql));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			 
			// Execute HTTP Post Request
			HttpResponse response = httpclient.execute(httppost);
			is = response.getEntity().getContent();
			try{
	            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
	            StringBuilder sb = new StringBuilder();
	            String line = null;
	            while ((line = reader.readLine()) != null) {
	                    sb.append(line + "\n");
	            }
	            is.close();
	            result=sb.toString();
			} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			}
		} catch (IOException e) {
		// TODO Auto-generated catch block
		}

	    try {	    	
			jArray = new JSONArray(result);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    return jArray;
	}
}
